// 全局变量
let friends;
let chat;
let socket;

/**
 * 初始化全局变量<br/>
 * friends  聊天列表<br/>
 * chat     聊天窗口<br/>
 */
function init() {
    friends = {
        list: document.querySelector('ul.people'),//聊天列表框
        all: document.querySelectorAll('.left .person'),//聊天列表对象
        name: ''
    };

    chat = {
        container: document.querySelector('.container .right'),
        current: null,
        person: null,
        name: document.querySelector('.container .right .top .name')
    };

    //初始化聊天对象和聊天记录
    document.querySelector('.chat').classList.add('active-chat');
    document.querySelector('.person').classList.add('active');

    friends.all.forEach(f => {
        //为每个聊天列表对象绑定切换聊天窗口事件
        f.addEventListener('mousedown', () => {
            f.classList.contains('active') || setActiveChat(f);//判断对象是否为聊天对象或者设置聊天对象
        });

        f.addEventListener('mousedown', function () {
            showChat(this);
        });

    });
}

/**
 * 设置聊天活跃用户
 * @param f 聊天对象
 */
function setActiveChat(f) {
    // 移除当前活跃用户
    friends.list.querySelector('.active').classList.remove('active');
    // 设置当前对象为活跃用户
    f.classList.add('active');
    // 获取聊天对象
    chat.person = f.getAttribute('data-chat');
    // 获取当前活跃聊天用户，并删除该聊天对象
    chat.current = chat.container.querySelector('.active-chat');
    chat.current.classList.remove('active-chat');
    // 获取聊天对象对应的聊天框并设置为活跃用户
    chat.container.querySelector('[data-chat="' + chat.person + '"]').classList.add('active-chat');
    // 获取聊天对象的名称，并设置聊天内容框头部的名称
    friends.name = f.querySelector('.name').innerText;
    chat.name.innerHTML = friends.name;
}

/**
 * 发送信息
 */
function sendMsg() {
    let currMsg = document.getElementById("contentInput").value;

    // 添加发送消息体
    addMsgBody(0, currMsg);
    // 获取当前聊天的人
    let currChatPerson = chat.container.querySelector('.active-chat').getAttribute('data-chat');
    if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        // 消息格式json字符串：{“to”：“xxx”,“content”：“xxx”}

        if (socket.readyState === 1) {
            console.log('{"toUserId":"' + currChatPerson + '","contentText":"' + currMsg + '"}');
            socket.send('{"to":"' + currChatPerson + '","content":"' + currMsg + '"}');
			document.getElementById("contentInput").value='';
        }


    }
}

/**添加消息体
 * @param {Object} a 接收方 or 发送方
 * @param {Object} b 消息
 */
function addMsgBody(a, b) {

    // 获取当前聊天的对象
    let currChatPerson = chat.container.querySelector('.active-chat').getAttribute('data-chat');
    //获取div——当前聊天对象的聊天框
    let currDiv = chat.container.querySelector('.active-chat');
    //添加div——聊天内容新加一个消息体
    let div2 = document.createElement("div");

    if (a === 0) { //发送方
        div2.setAttribute("class", "bubble me");
    } else { //接收方
        div2.setAttribute("class", "bubble you");
        // 接收方渲染接收数据
        // currDiv = document.getElementById("chat-" + jQuery.parseJSON(b).fromUserId);
        // b = jQuery.parseJSON(b).contentText;
    }
    div2.innerText = b.toString();

    // 在当前聊天对象中的聊天框中加入消息
    currDiv.appendChild(div2);
    // 清空消息输入框
    document.getElementById("contentInput").value = "";
}

// 绑定键盘按钮事件
document.onkeydown = function (e) {
    if (e.code === 'Enter') {
        sendMsg();
    }
}

function openSocket() {
    if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    } else {
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
        //let socketUrl = "	https://xxx.xxx.com/webSocketServer/" + document.getElementById("logginUser").value;

		// let ws = "ws://localhost:8080/ws/";
		// let token = localStorage.getItem("token");
		
		// let socketUrl = ws + token;

        let socketUrl = "ws://localhost:8080/ws/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NjA3NTU3NzcsInVzZXJuYW1lIjoiMTk5ODM0NTUxMTEifQ.82U_UXjLgMGSiDe-yWyIOJfhIBnzCQJs86KBcH31FVQ";
        console.log(socketUrl);
        if (socket != null) {
            socket.close();
            socket = null;
        }
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
            console.log("websocket已打开");
        };
        //获得消息事件
        socket.onmessage = function (msg) {
            console.log(msg.data);
            //发现消息进入    开始处理前端触发逻辑
            addMsgBody(1, msg.data);
        };

        //关闭事件
        socket.onclose = function () {
            console.log("websocket已关闭");
            openSocket();
        };

        //发生了错误事件
        socket.onerror = function () {
            console.log("websocket发生了错误");
        }
    }
}

/**
 * 展示聊天列表
 */
function showList() {
    let list = $(".people");
    let write = $(".write");

    $.ajax({
        url: "http://localhost:8080/seeker/chat_message/showUserChatList",
        type: "POST",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NjA3NTU3NzcsInVzZXJuYW1lIjoiMTk5ODM0NTUxMTEifQ.82U_UXjLgMGSiDe-yWyIOJfhIBnzCQJs86KBcH31FVQ");
        },
        success: function (result) {
            if (result.code === 0) {//查询成功，显示查询数据，失败，显示静态数据
                list.empty();//清空当前静态页面中的数据
                for (let i = 0; i < result.data.length; i++) {
                    let li = $("<li class='person'></li>");
                    let img = $("<img alt=''/>");
                    let span = $("<span class='name'></span>")

                    let div = $("<div class='chat'></div>");
                    div.attr("data-chat", result.data[i].phone);
                    div.attr("jid", result.data[i].jid);
                    div.attr("cid", result.data[i].cid);
                    div.insertBefore(write);

                    img.attr("src", result.data[i].seekerPhoto);
                    li.attr("data-chat", result.data[i].phone);
                    li.attr("jid", result.data[i].jid);
                    li.attr("cid", result.data[i].cid);
					if(result.msg === "1" ){
						span.text(result.data[i].recruitersName);
					}
                    if( result.msg === "2" ){
						span.text(result.data[i].seekerName);
					}
                    li.append(img);
                    li.append(span);
                    list.append(li);
                }
            }
            //初始化参数
            init();
        }
    })
}

/**
 * 展示聊天框内容
 * @param obj 事件源对象
 */
function showChat(obj) {
    let dc = obj.getAttribute("data-chat")
    let text = $(".active .name").text();
    $(".top .name").text(text);
    $.ajax({
        url: "http://localhost:8080/seeker/chat_message/showChatListByPhone",
        data: {
            "phone": dc
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NjA3NTU3NzcsInVzZXJuYW1lIjoiMTk5ODM0NTUxMTEifQ.82U_UXjLgMGSiDe-yWyIOJfhIBnzCQJs86KBcH31FVQ");
        },
        success: function (result) {
            let selected = $("div[data-chat=" + dc + "]");
            //聊天开始时间
            let timeDiv = $("<div class='conversation-start'></div>")
            let timespan = $("<span></span>");
            timespan.text(result.data[0].createTime);
            timeDiv.append(timespan);
            selected.append(timeDiv);

            for (let i = 0; i < result.data.length; i++) {
                // let recordDiv = $("<div></div>");
                // 发送方和当前聊天对象一致，消息在左边，不一致在右边
                if (result.data[i].sendUser === dc)
                    addMsgBody(1, result.data[i].content)
                else
                    addMsgBody(0, result.data[i].content);
            }

            init();
        }
    })
}

openSocket();

function sendResume() {
    let currDiv = chat.container.querySelector('.active-chat');
    let cid = currDiv.getAttribute("cid");
    let jid = currDiv.getAttribute("jid");
    console.log(cid)
    console.log(jid)
    $.ajax({})
}


showList();


